//
//  BaseNavigationController.swift
//  Pastime
//
//  Created by 🐑 on 2018/11/20.
//  Copyright © 2018 Zhu. All rights reserved.
//

import UIKit

class BaseNavigationController: UINavigationController {

    var popDelegate: UIGestureRecognizerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        initController()
    }
    
    // MARK: - 初始化
    private func initController() {
        delegate = self
        popDelegate = interactivePopGestureRecognizer?.delegate
        view.backgroundColor = .white
        navigationBar.tintColor = .white
        navigationBar.barTintColor = .main
        navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)]
    }
    
    deinit {
        print("\(type(of: self)) --> deinit")
    }
}

// MARK: - 私有方法
private extension BaseNavigationController {
    
    @objc func pop() {
        popViewController(animated: true)
    }
}

// MARK: - 协议
extension BaseNavigationController: UINavigationControllerDelegate {
    
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        let isRootContoller = (viewController == navigationController.viewControllers.first)
        if !isRootContoller {
            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "back"), style: .done, target: self, action: #selector(pop))
        }
    }
    
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        let isRootContoller = (viewController == navigationController.viewControllers.first)
        if isRootContoller {
            interactivePopGestureRecognizer?.delegate = popDelegate
        } else {
            interactivePopGestureRecognizer?.delegate = nil
        }
    }
}
